<template>
  <AdminHeader />
  <div>
    <div class="container-fluid">
      <div class="row text-center justify-content-center webtitle"></div>
      <div class="row justify-content-center">
        <div class="avatar-uploader-container">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
        <div class="row">
          <p class="upload-tip">点击上面的上传框可以 上传/更换 图片</p>
        </div>
        <el-form ref="novelForm" :rules="rules" :model="form" label-width="auto" @submit.prevent="addNovel" style="max-width: 90%">
          <el-form-item label="小说名称" prop="novel_name" required>
            <el-input v-model="form.novel_name" clearable required></el-input>
          </el-form-item>
          <el-form-item label="小说描述" prop="novel_desc" required>
            <el-input type="textarea" v-model="form.novel_desc" clearable required></el-input>
          </el-form-item>
          <el-form-item label="小说类型" prop="novel_type" required>
            <el-input v-model="form.novel_type" required clearable></el-input>
          </el-form-item>
          <el-form-item label="小说封面链接" prop="novel_pic" v-if="isPicInputHidden">
            <el-input v-model="form.novel_pic" clearable disabled></el-input>
          </el-form-item>
          <el-form-item label="小说默认作者" prop="novel_name" required>
            <el-input v-model="form.nickname" clearable disabled></el-input>
          </el-form-item>
          <el-form-item class="text-center" style="width: 100%">
            <el-button type="primary" native-type="submit" style="width: 120px; margin: 0 auto;">增加</el-button>
          </el-form-item>
          <el-form-item class="text-center" style="width: 100%">
            <el-button @click="goBack" style="width: 120px; margin: 0 auto;">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import axios from 'axios';
import VueCookies from "vue-cookies";
import {ElNotification} from "element-plus";
import {Plus} from '@element-plus/icons-vue';
import AdminHeader from "@/components/AdminHeader.vue";
import config from "../../../config/config.js";

const form = ref({
  nickname: '',
  novel_name: '',
  novel_desc: '',
  novel_type: '',
  novel_pic: ''
});
VueCookies.set('activeIndex',3);
const router = useRouter();
const imageUrl = ref('');
const isPicInputHidden = ref(false);
const userToken = ref('');
const adminToken = VueCookies.get('adminToken');
const userId = ref('zsy');
const uploadUrl = ref(`${config.apiUrl}/upload/images`);
const rules = {
  novel_name: [
    {required: true, message: '小说名称不能为空', trigger: 'blur'},
    // 其他验证规则
  ],
  novel_desc: [
    {required: true, message: '小说描述不能为空', trigger: 'blur'},
    // 其他验证规则
  ],
  novel_type: [
    {required: true, message: '小说类型不能为空', trigger: 'blur'},
    // 其他验证规则
  ],
  novel_pic: [
    {required: true, message: '小说封面图片不能为空', trigger: 'change'},
  ]
};
const fetchDefaultUserInfo = async () => {      //获取默认用户名为zsy，所有新增小说为username：zsy的小说

  const apiUrl = `${config.apiUrl}/user/search?username=${userId.value}&type=3`;

  try {
    const getuinfo = await axios.get(apiUrl, {
      headers: {
        'Authorization': `Bearer ${adminToken}` // 使用 Cookie 中的 Token
      },
    });
    const userInfo = getuinfo.data[0];
    form.value.nickname = userInfo.nickname;

    //get userToken
    const loginres = await axios.post(`${config.apiUrl}/user/login`, {
      username: userInfo.username,
      password: userInfo.password,
    });

    if (loginres.data.token) {
      // 如果登录成功，存储 token 在 cookie 中，过期时间为 10 天
      userToken.value = loginres.data.token;
      //console.log(userToken.value);
    }

  } catch (error) {
    ElNotification({
      message: '获取默认用户信息失败',
      type: 'error',
      duration: 1000
    });
    goBack();
  }
};

const addNovel = async () => {
  if (!form.value.novel_pic) {
    ElNotification({
      message: '小说封面图必须上传 ~',
      type: 'warning',
      duration: 2000
    });
    return;
  }
  const userToken = VueCookies.get('userToken');
  const apiUrl = `${config.apiUrl}/novel/add`;
  const headers = {
    Authorization: `Bearer ${userToken}`
  };

  try {
    const response = await axios.post(apiUrl, form.value, {headers});
    if (response.status === 200) {
      ElNotification({
        message: response.data.message,
        type: 'success',
        duration: 2000
      });
      // 成功后跳转到列表页或其他页面
      goBack();
    } else {
      ElNotification({
        message: response.data.message,
        type: 'error',
        duration: 1400
      });
    }
  } catch (error) {
    ElNotification({
      message: error,
      type: 'error',
      duration: 2000
    });
  }
};

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = response.filePath;
  form.value.novel_pic = response.filePath;
  ElNotification({
    message: '上传成功！',
    type: 'success',
    duration: 2000
  });
  isPicInputHidden.value = true;
};
const goBack = () => {
  router.back();
};
const beforeAvatarUpload = (rawFile) => {
  const allowedExtensions = ['png', 'jpg', 'webp'];
  const extension = rawFile.name.split('.').pop();
  if (!allowedExtensions.includes(extension)) {
    ElNotification({
      message: '无效文件: Invalid file extension',
      type: 'error',
      duration: 2000
    });
    return false;
  }
  return true;
};
onMounted(fetchDefaultUserInfo);
</script>

<style scoped>
.webtitle {
  font-size: 15px;
  padding: 10px;
}

.avatar-uploader-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .avatar {
  width: 128px;
  height: 160px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 178px;
  text-align: center;
  border: 1px dotted lightgrey;
}

.upload-tip {
  text-align: center;
  margin-top: 10px;
  font-size: 14px;
  color: grey;
}
</style>
